package com.zuilapsa.jmc.actions;

import org.dom4j.Element;

import com.zuilapsa.jmc.JmcException;
import com.zuilapsa.jmc.exporters.ExporterBean;
import com.zuilapsa.jmc.exporters.ExporterInterface;


public class ActionProducer {
	protected static ActionProducer producer = null;

	private ActionProducer() {

	}

	public static ActionInterface getAction(Element element) throws JmcException {
		return getInstance().getActionInstance(element);
	}

	protected ActionInterface getActionInstance(Element element) throws JmcException {
		ActionInterface classInstance = null;
		try {
//			String className = element.attributeValue("class");
//			Class classClass = Class.forName(className);
//			classInstance = (ActionInterface)classClass.newInstance();
			
			String actionName = element.attributeValue("name");
			String className = element.attributeValue("class");
			String scriptName = element.attributeValue("script");
			if (actionName == null) {
				throw new JmcException("Lack of name attribute in action definition");
			}
			if (scriptName != null && className != null) {
				throw new JmcException("Abigous action definition: "+element.asXML());
			}
			if (className != null) { 
				Class classClass = Class.forName(className);
				classInstance = (ActionInterface)classClass.newInstance();
			}
			if (scriptName != null) {
				classInstance = new ActionBean(actionName, scriptName);
			}

		} catch (ClassNotFoundException e) {
			System.err.println("The action was not found");
			throw new JmcException("The action was not found", e);
		} catch (Exception e) {
			System.err.println("The action happend to be wrong");
			throw new JmcException("The action happend to be wrong", e);
		}
		classInstance.setDefinition(element);
		return classInstance;
	}

	public static ActionProducer getInstance() {
		if (producer == null) {
			producer = new ActionProducer();
		}
		return producer;
	}
}
